import React, { useState } from 'react';
import { createModel } from 'hox';
import { message } from 'antd';
import {
  queryDevice,
  querySpData,
  deleteAlarmAPI,
  queryAlarmsBySu,
  getWsAddr,
  command,
} from '../service.js';
import { useRequest } from '@umijs/hooks';
import websocketHeartbeatJs from '@/utils/websocker';
import Stomp from 'stompjs';
import SockJS from 'sockjs-client';

class Field {
  monitoringVisible = false;
  suItemData = {};
  subDevList = [];
  spList = [];
  alarmList = [];
  websocket = null;
  subDevIndex = null;
  subDevRow = {};
  selectedRowKeys = [];
}
function useFlowModel() {
  const field = new Field();

  const [state, dispatch] = useState({
    ...field,
  });
  const setMonitorState = payload => {
    dispatch(prevState => ({ ...prevState, ...payload }));
  };

  //获取子设备
  const { run: getSubDevData, loading: devLoading, refresh: refreshSubDevData } = useRequest(
    queryDevice,
    {
      manual: true,
      onSuccess: (res, params) => {
        if (res.result) {
          setMonitorState({ subDevList: res.data || [] });
        } else {
          message.error(res.msg);
        }
      },
    },
  );

  //获取监控点
  const { run: getSpData, loading: spLoading } = useRequest(querySpData, {
    manual: true,
    onSuccess: (res, params) => {
      if (res.result) {
        setMonitorState({ spList: res.data || [] });
      } else {
        message.error(res.msg);
      }
    },
  });
  //更新监控点列表
  const updateSpList = (index, row) => {
    setMonitorState({
      subDevIndex: index,
      subDevRow: row,
    });

    let current = state.subDevList.filter((item, i) => {
      return index === i;
    });
    getSpData({ id: current[0].id });
  };
  //下发命令
  const { run: postCommand } = useRequest(command, {
    manual: true,
    onSuccess: (res, params) => {
      if (res.result) {
        return res;
      } else {
        message.error(res.msg);
      }
    },
  });
  //删除告警
  const { run: deleteAlarm } = useRequest(deleteAlarmAPI, {
    manual: true,
  });
  //获取监控点
  const { run: getAlarmsBySu, loading: alramLoading } = useRequest(queryAlarmsBySu, {
    manual: true,
  });
  //获取监控数据
  const getMonitorData = async suItemData => {
    let row = localStorage.getItem('deviceType');
    if (row) {
      let res = await getSubDevData({
        suId: suItemData.suId,
        fsuTypeId: JSON.parse(row)?.id,
      });

      if (res.result && res?.data && res.data[0]) {
        setMonitorState({
          subDevIndex: 0,
          subDevRow: res.data[0],
        });
        getSpData({
          id: res.data[0].id,
        });
      }
      let wsAddr = await getWsAddr();
      let alarm = await getAlarmsBySu({ suIndex: suItemData.id });

      if (wsAddr.result && wsAddr?.data) {
        createSocket(suItemData.suId, setMonitorState, wsAddr?.data?.ip, row);

        setMonitorState({ alarmList: alarm.data || [] });
      }
      //建立websocket;
    }
  };
  const clear = () => {
    setMonitorState({ ...new Field() });
  };

  return {
    ...state,
    clear,
    updateSpList,
    refreshSubDevData,
    devLoading,
    alramLoading,
    getAlarmsBySu,
    setMonitorState,
    getMonitorData,
    postCommand,
    spLoading,
    deleteAlarm,
  };
}
const createSocket = (id, setState, ip) => {
  if (!ip) {
    return;
  }
  let socket = null;
  let stompClient = null;
  const connect = () => {
    socket = new SockJS(
      `http://${ip}:9999/websocket?userId=${id}:${
        JSON.parse(localStorage.getItem('deviceType') || {}).id
      }`,
    ); //WebSocket对应的地址

    stompClient = Stomp.over(socket);
    //定义连接函数
    if (stompClient == null || !stompClient.connected) {
      const headers = {};
      stompClient.reconnect_delay = 20000;
      stompClient.heartbeat.outgoing = 20000;
      stompClient.heartbeat.incoming = 0;
      stompClient.connect(headers, connectCallback, errorCallback);
    } else {
      console.log('当前处于连接状态');
    }
    setState({ websocket: stompClient });
  };
  const connectCallback = frame => {
    //连接成功时的回调函数
    console.log('Connected: ' + frame);
    //订阅AAA频道
    stompClient.subscribe('/user/queue/alarms', function(greeting) {
      //后台传过来的json字符串转换为json对象

      if (greeting.body) {
        const res = JSON.parse(greeting.body);
        const data = res?.data || [];
        setState({ alarmList: data || [] });
      }
    });
  };
  const errorCallback = () => {
    //连接失败时的回调函数，此函数重新调用连接方法，形成循环，直到连接成功
    connect();
  };
  connect();
  return socket;
};

export default createModel(useFlowModel);
